<template>
  <div class="camera-box" style="width: 900px;">
    <div style="text-align: center;font-size: 14px;font-weight: bold;margin-bottom: 10px;  font-size: 20px;">查询到当前用户还有<span style="color:red">{{number}}</span>涨待缴单未缴费</div>
    <el-row :gutter="20">
      <el-col :span="12">
        <div style="text-align: center;font-size: 14px;font-weight: bold;margin-bottom: 10px;">摄像头</div>
        <!-- 这里就是摄像头显示的画面 -->
        <video id="video" width="400" height="300"></video>
        <div class="iCenter" >
          <el-button type='primary' size='small' icon="el-icon-camera" @click="takePhone" style="margin-top: 10px;">拍照</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div style="text-align: center;font-size: 14px;font-weight: bold;margin-bottom: 10px;">拍摄效果</div>
        <!-- 这里是点击拍照显示的图片画面 -->
        <canvas id='canvas' width='400' height='300' style="display: block;"></canvas>
        <el-button :loading="loadingbut" icon="el-icon-check" type='primary' size='small' @click="takePhoneUpfile" style="margin-top: 10px;">{{saveText}}</el-button>
      </el-col>
    </el-row>
</div>
</template>
<script>
import { upload } from '@/api/upload'
import { hideLoading, showLoading } from '@/utils'
export default {
  props: {
    tackPhoto: { // 父组件传过来的状态
      type: Boolean,
      default: false
    },
    saveText: {
      type: String,
      default: '保存'
    },
    number: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      loadingbut: false,
      preViewVisible: false,
      blobFile: null,
      canvas: null,
      video: null,
      mediaStreamTrack: ''
    }
  },
  watch: {
    tackPhoto: {
      immediate: true,
      handler (newVal) { // 监听接收到拍摄状态后，开始调取摄像头权限。如果功能是在一个组件里面，下面步骤可以直接写在自己的触发方法里面
        console.log('Value', newVal)
        if (newVal) {
          var video = document.querySelector('video')
          //   var text = document.getElementById('text')
          // var mediaStreamTrack;

          // 兼容代码
          window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL)

          if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {}
          }
          if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function(constraints) {
              var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia
              if (!getUserMedia) {
                return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
              }
              return new Promise(function(resolve, reject) {
                getUserMedia.call(navigator, constraints, resolve, reject)
              })
            }
          }

          // 摄像头调用配置
          var mediaOpts = {
            audio: false,
            // video: true,
            video: { facingMode: 'user' } // 或者 "user"
            // video: { width: 1280, height: 720 }
            // video: { facingMode: { exact: "environment" } }// 或者 "user"
          }

          let that = this
          navigator.mediaDevices.getUserMedia(mediaOpts).then(function(stream) {
            that.mediaStreamTrack = stream
            video = document.querySelector('video')
            if ('srcObject' in video) {
              video.srcObject = stream
            } else {
              video.src = window.URL && window.URL.createObjectURL(stream) || stream
            }
            video.play()
          }).catch(function (err) {
            console.log(err)
          })
        } else {
          this.cancalCloseVideo()
        }
      },
      deep: true
    }
  },
  mounted() {
    // 摄像头
    this.video = document.getElementById('video')
    // 画布
    this.canvas = document.getElementById('canvas')
  },
  methods: {

    takePhone() { // 点击拍照截图画面
      let that = this
      if (!this.tackPhoto) {
        this.$message('查询到当前用户还有待缴单未缴费')
        return
      }
      that.canvas.getContext('2d').drawImage(this.video, 0, 0, 400, 300)
      let dataurl = that.canvas.toDataURL('image/jpeg')
      that.blobFile = that.dataURLtoFile(dataurl, Date.now() + 'camera.jpg')
      that.preViewVisible = true
    },
    dataURLtoFile (dataurl, filename) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    takePhoneUpfile() { // 保存图片
      if (!this.tackPhoto) {
        this.$message('查询到当前用户还有待缴单未缴费')
        return
      }
      this.loadingbut = true
      let formData = new FormData()
      formData.append('file', this.blobFile)// 图片内容
      // 上传图片
      showLoading()
      return upload(this.blobFile).then(res => {
        hideLoading()
        this.loadingbut = false
        console.log('res', res)
        var link = res.data.detail.link
        this.$emit('fatherMethod', link)
        let detail = res.data.detail
        return detail
      }).catch((err) => {
        hideLoading()
        this.loadingbut = false
        // console.log(err)
        // 上传错误可⾃⾏给出提⽰
        if (err.message) {
          this.$message.error(err.message)
        }
        return Promise.reject(err)
      })
      // putFileAttach(formData).then(res => { // 后台接口
      //   this.loadingbut = false
      //   this.$emit('picture', res.data.data)
      //   this.tackPhoto = false
      //   this.canvas.getContext('2d').clearRect(0, 0, 400, 300)// 清除画布
      //   // 关闭摄像头
      //   this.mediaStreamTrack.getVideoTracks().forEach(function (track) {
      //     track.stop()
      //   })
      // }, error => {
      //   this.loadingbut = false
      //   window.console.log(error)
      // })
    },
    // 关闭摄像头
    cancalCloseVideo() {
      var that = this
      if (that.number > 0) {
        // this.$message('查询到当前用户还有待缴单未缴费')
        return
      }
      this.canvas.getContext('2d').clearRect(0, 0, 400, 300)
      // 关闭摄像头
      this.mediaStreamTrack.getVideoTracks().forEach(function (track) {
        track.stop()
      })
    }
  }
}
</script>
<style>
#video {
      transform: rotateY(180deg);
    }
 .camera-box #canvas{
  border: 1px solid #DCDFE6;
  }
</style>
